﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
using System.Globalization;
using System.Xml;

namespace ResUma
{
    public partial class ExportDeclaratiiFrm : FrmRezumat 
    {
        private String CaleD394 = String.Empty;
        private List<String> lista_CUI = new List<String>();
        private XmlDocument xmlDoc = new XmlDocument();
        public ExportDeclaratiiFrm(ModuleClass mc) : base(mc)
        {
            workConnString = mc.workConnectionString;
            InitializeComponent();
            declaratieCB.Items.Add("D205");
            anulDTP.Format = DateTimePickerFormat.Custom;
            anulDTP.CustomFormat = "yyyy";
            semestrulCB.Items.Add("semestrul 1");
            semestrulCB.Items.Add("semestrul 2");
            
            trimestrulCB.Items.Add("trimestrul I");
            trimestrulCB.Items.Add("trimestrul II");
            trimestrulCB.Items.Add("trimestrul III");
            trimestrulCB.Items.Add("trimestrul IV");

            SmartCardCB.Items.Add("aladdin");
            SmartCardCB.Items.Add("athena");
            SmartCardCB.Items.Add("gemalto");
            SmartCardCB.Items.Add("oberthur");
            SmartCardCB.Items.Add("safeNet");
            SmartCardCB.Items.Add("schlumberger");
            SmartCardCB.SelectedIndex = 0;
            
            lunaCB.Items.AddRange(new String[] {"Ianuarie","Februarie","Martie","Aprilie","Mai","Iunie","Iulie","August","Septembrie","Octombrie","Noiembrie","Decembrie"});
            semestrulCB.SelectedIndex = 0;
            trimestrulCB.SelectedIndex = 0;
            lunaCB.SelectedIndex = 0;
            semestrulRB.Checked = true;

            delaDTP.Format = DateTimePickerFormat.Custom;
            delaDTP.CustomFormat = "dd.MM.yyyy";
            panalaDTP.Format = DateTimePickerFormat.Custom;
            panalaDTP.CustomFormat = "dd.MM.yyyy";

        }

        private void ExportDeclaratiiFrm_Load(object sender, EventArgs e)
        {
            AddButton("Proceseaza[F9]", global::ERPStudio.Properties.Resources.gear, Proceseaza, ToolStripItemAlignment.Right, true);
            AddButton("Info Unitate", global::ERPStudio.Properties.Resources._001_55, Info, ToolStripItemAlignment.Right, true);
            declaratieCB.SelectedIndex = 0;
            SqlConnection wConn = DeschideConexiune(workConnString);
            #region Determinare luna,an curent
            Object ret = GetSetupValue("FaresSetup", "CaleD394", ModuleInfo.CodUnitate, wConn);
            String val = String.Empty;
            if (ret != null && ret != DBNull.Value)
                val = ret.ToString();
            else
            {
                //while (ret == null)
                //{
                //    MessageBox.Show("Modulul Parteneri nu a fost configurat. \nVa rugam sa-l configurati!",
                //            "Eroare",
                //            MessageBoxButtons.OK,
                //            MessageBoxIcon.Hand);
                //    FaresSetupFrm frm = new FaresSetupFrm(this.ModuleInfo);
                //    frm.ShowDialog();
                //    ret = GetSetupValue("FaresSetup", "CaleD394", ModuleInfo.CodUnitate, wConn);
                //}
            }
            CaleD394 = ret.ToString();
            #endregion
            InchideConexiune(wConn);
        }

        private void Proceseaza(object sender, EventArgs e)
        {
            if (declaratieCB.SelectedIndex == 0)
            {
                //face backup la fisierul existent
               
                String NumeFisierXml = CaleD394 + "D205.xml";
                String sem;
                xmlDoc.AppendChild(xmlDoc.CreateProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"));
                
                String sb = "<?xml version=\"1.0\"?>\n<declaratie205 xmlns=\"mfp:anaf:dgti:d205:declaratie:v1\" xsi:schemaLocation=\"mfp:anaf:dgti:d205:declaratie:v1 d205.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ";
                using(SqlConnection wCon = DeschideConexiune(workConnString))
                {
                    this.unitatiTableAdapter.Connection = wCon;
                    this.unitatiTableAdapter.Fill(this.eSRPDataSetListe.Unitati, ModuleInfo.CodUnitate);
                    if (unitatiBindingSource.Count == 0)
                    {
                        MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "Modulul nu a fost configurat inca!", String.Empty,MessageBoxFrm.ImaginiMB.StopIcon, null);
                        mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                        mbt.ShowDialog();
                        // modulul nu este configurat
                        return;
                    }
                    ESRPDataSetListe.UnitatiRow ur = ((DataRowView)unitatiBindingSource.Current).Row as ESRPDataSetListe.UnitatiRow;

                    String sbi = " mail=\"" + (ur.IsEmailNull() ? "" : ur.Email) + "\" ";
                    sbi += " fax=\"" + (ur.IsFaxNull() ? "" : ur.Fax) + "\" ";
                    sbi += " telefon=\"" + (ur.IsTelefonNull() ? "" : ur.Telefon) + "\" ";
                    sbi += " adresa=\"" + (ur.IsAdresaNull() ? "" : ur.Adresa) + "\" ";
                    sbi += " den=\"" + ur.Denumire + "\" ";
                    sbi += " cui=\"" + ur.CUI + "\" ";




                    String sb6 = String.Empty;
                   

                    String nume = String.Empty, prenume = String.Empty;
                    int retspa = ur.Reprezentant.IndexOf(' ');
                    if (retspa != -1)
                    {
                        nume = ur.Reprezentant.Substring(0, retspa);
                        prenume = ur.Reprezentant.Substring(retspa + 1);
                    }
                   
                    String[] pozR = ur.Reprezentant.ToString().Split(new char[]{' '});
                    
                    sb6 += " functie_declar=\"" + (ur.IsFunctieReprezentantNull()?"Administrator":ur.FunctieReprezentant) + "\" ";
                    if (pozR.Length >= 1)
                    {
                        sb6 += " nume_declar=\"" + pozR[0] + "\" ";
                    }
                    if (pozR.Length >= 2)
                    {
                        sb6 += " prenume_declar=\"" + pozR[1] + "\" ";
                    }

                    sb6 += " d_rec=\"" + (RectificativaCB.Checked ? "1" : "0") + "\" ";
                    sb6 += " an=\"" + anulDTP.Value.Year.ToString() + "\" ";
                    sb6 += " luna=\"12\">";

                    

                    Decimal? totBC = Decimal.Zero, totI = Decimal.Zero;
                    Int32? nrBen=0;
                    
                    this.dsc_GenDecl205TableAdapter.Connection = DeschideConexiune("PersSalConnectionString");
                    this.dsc_GenDecl205TableAdapter.Fill(this.persSalDataSet.dsc_GenDecl205,
                        anulDTP.Value.Year,ref totBC, ref totI,ref nrBen);

                   


                    String sb2 = String.Empty;
                    int CateLinii = 0;
                    lista_CUI.Clear();
                    foreach(DataRowView drv in dsc_GenDecl205BindingSource)
                    {
                        PersSalDataSet.dsc_GenDecl205Row fr = drv.Row as PersSalDataSet.dsc_GenDecl205Row;

                        String den = fr.Nume_Pren.Replace("&", "and");
                        sb2 += "\n<benef imp1=\"" + Convert.ToDouble(fr.Impozit).ToString("F0", (CultureInfo.InvariantCulture)) + "\" baza1=\"" +
                            Convert.ToDouble(fr.VenitBC).ToString("F0", (CultureInfo.InvariantCulture)) + "\"";
                        if (fr.TipContr==1)
                        {
                             sb2 += " dedu_alte=\"" +
                                Convert.ToDouble(fr.Altededuceri).ToString("F0", (CultureInfo.InvariantCulture)) + "\" dedu_pers=\"" +
                                Convert.ToDouble(fr.DeduceriPersonale).ToString("F0", (CultureInfo.InvariantCulture)) + "\""; 
                        }
                        else
                            sb2 += " dedu_alte=\"0\" dedu_pers=\"0\""; 

                        sb2 += " vbrut=\"" + 
                        Convert.ToDouble(fr.VenitBrutAnual).ToString("F0", (CultureInfo.InvariantCulture)) + "\" tip_functie=\"" + 
                        Convert.ToDouble(fr.TipContr).ToString("F0", (CultureInfo.InvariantCulture)) + "\" tip_plata=\"2\" den1=\"" + 
                        fr.Nume_Pren + "\" cif1=\"" + fr.CNP + "\" tip_venit1=\"07\" />";
                        
                        if (!lista_CUI.Contains(fr.CNP))
                        {
                            
                            lista_CUI.Add(fr.CNP);
                        }
                        CateLinii++;

                    }


                    Decimal totalG = Decimal.Zero;
                    //<rezumat tvaCc="0" bazaCc="0" tvaC="0" bazaC="0" tvaVc="0" bazaVc="0" tvaV="0" bazaV="0" tvaA="192456" bazaA="801900" tvaL="25661" bazaL="106920" nrCui="2"/>
                    String sb1 = "\n<sect_II ";
                    if (totI.HasValue)
                    {
                        sb1 += "Timp=\"" + Convert.ToDouble(totI.Value).ToString("F0", (CultureInfo.InvariantCulture))+ "\" ";
                    }
                    else
                        sb1 += "Timp=\"0\" ";

                    if (totBC.HasValue)
                    {
                        sb1 += "Tbaza=\"" + Convert.ToDouble(totBC.Value).ToString("F0", (CultureInfo.InvariantCulture)) + "\" ";
                    }
                    else
                        sb1 += "Tbaza=\"0\" ";
                    sb1+= " Tpierd=\"0\" Tcastig=\"0\" ";
                    if (nrBen.HasValue)
                    {
                        sb1 += "nrben=\"" + Convert.ToDouble(CateLinii).ToString("F0", (CultureInfo.InvariantCulture)) + "\" ";
                    }
                    else
                        sb1 += "nrben=\"0\" ";
                    sb1+= " tip_venit=\"07\"/>";

                    if (totI.HasValue && totBC.HasValue && nrBen.HasValue)
                    {
                        sb += "totalPlata_A=\"" + Convert.ToDouble(totI.Value + totBC.Value + CateLinii).ToString("F0", (CultureInfo.InvariantCulture)) + "\" ";
                    }
                    else
                        sb += "totalPlata_A=\"0\" ";


                    sb += sbi + sb6+ sb1 + sb2 + "\n</declaratie205>";
                    try
                    {
                        xmlDoc.LoadXml(sb);
                    }
                    catch(Exception ex)
                    {

                        TrateazaExceptie(ex,sb);
                        return;
                    }
                }
                xmlDoc.Save(NumeFisierXml);
                
                try
                {
                    //presupunem ca nu are parametrii
                    String savedir = Directory.GetCurrentDirectory();
                    //java -version:1.6 -jar "C:\dist\DUKIntegrator.jar" -s D112 C:/D112.xml $ 0 0 $ 1234 aladdin
                    ProcessStartInfo startInfo = new ProcessStartInfo("java");
                    startInfo.Arguments = "-jar \"" + CaleD394 + "DUKIntegrator.jar\" -p D205 \"" + NumeFisierXml + "\" $ 0 0 $ ";
                    if (SemnatCB.Checked)
                    {
                        startInfo.Arguments = "-jar \"" + CaleD394 + "DUKIntegrator.jar\" -s D205 \"" + NumeFisierXml + "\" $ 0 0 $ " + 
                            PasswordTB.Text + " " + SmartCardCB.Text;
                    }

                    startInfo.WorkingDirectory = CaleD394;
                    MyTrace("Start: " + startInfo.FileName + " args: " + startInfo.Arguments + " working dir: " + startInfo.WorkingDirectory);
                    Process.Start(startInfo);
                    MyTrace("Revenire director aplicatie: " + savedir);
                    Directory.SetCurrentDirectory(savedir);
                }
                catch (Exception ex)
                {
                    MyTrace(ex.Message);
                    if (ex.Message == "The system cannot find the file specified")
                    {
                        MessageBox.Show("Va rugam sa setati calea de lansare a programului DUKIntegrator din meniul Parametrizare Modul!","Atentie");
                        return;
                    }
                    MessageBox.Show(ex.ToString());
                    return;
                }
                MessageBox.Show("S-a generat fisierul: " + NumeFisierXml);
            }


        }

        private void Info(object sender, EventArgs e)
        {
            FrmMainMdi frm = this.MdiParent as FrmMainMdi;
            Assembly asm = frm.GetModule("erpforms");
            if (asm == null)
                return;
            String numeClasa = "ERPForms.UnitatiInfoFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {
                FrmCard newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                    new object[] { ModuleInfo, ModuleInfo.CodUnitate }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmCard;
                newFrm.ShowDialog();
            }
            
        }

        private void semestrulCB_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (semestrulCB.SelectedIndex == 0)
            {
                delaDTP.Value = new DateTime(anulDTP.Value.Year, 1, 1);
                panalaDTP.Value = new DateTime(anulDTP.Value.Year, 6, 30);
                return;
            }
            if (semestrulCB.SelectedIndex == 1)
            {
                delaDTP.Value = new DateTime(anulDTP.Value.Year, 7, 1);
                panalaDTP.Value = new DateTime(anulDTP.Value.Year, 12, 31);
                return;
            }


        }

        private void trimestrulRB_CheckedChanged(object sender, EventArgs e)
        {
            if (sender == semestrulRB)
            {
                semestrulCB.Enabled = true;
                trimestrulCB.Enabled = false;
                lunaCB.Enabled = false;
                delaDTP.Value = new DateTime(anulDTP.Value.Year, 1, 1);
                panalaDTP.Value = new DateTime(anulDTP.Value.Year, 6, 30);
                semestrulCB.SelectedIndex = 0;
            }
            else
                if (sender == trimestrulRB)
                {
                    semestrulCB.Enabled = false;
                    lunaCB.Enabled = false;
                    trimestrulCB.Enabled = true;
                    delaDTP.Value = new DateTime(anulDTP.Value.Year, 1, 1);
                    panalaDTP.Value = new DateTime(anulDTP.Value.Year, 3, 31);
                    trimestrulCB.SelectedIndex = 0;
                }
                else
                    if (sender == lunaRB)
                    {
                        semestrulCB.Enabled = false;
                        trimestrulCB.Enabled = false;
                        lunaCB.Enabled = true;
                        delaDTP.Value = new DateTime(anulDTP.Value.Year, 1, 1);
                        panalaDTP.Value = new DateTime(anulDTP.Value.Year, 1, 31);
                        lunaCB.SelectedIndex = 0;
                    }
        }

        private void trimestrulCB_SelectedIndexChanged(object sender, EventArgs e)
        {

            DateTime ultima = new DateTime(((trimestrulCB.SelectedIndex + 1) * 3 + 1) > 12?anulDTP.Value.Year:anulDTP.Value.Year+1,
                ((trimestrulCB.SelectedIndex + 1) * 3 + 1) > 12 ? 1 : (trimestrulCB.SelectedIndex + 1) * 3 + 1, 1);
            delaDTP.Value = new DateTime(anulDTP.Value.Year, trimestrulCB.SelectedIndex*3+1, 1);
            panalaDTP.Value = new DateTime(anulDTP.Value.Year, (trimestrulCB.SelectedIndex+1) * 3 , ultima.AddDays(-1).Day);
        }

        private void lunaCB_SelectedIndexChanged(object sender, EventArgs e)
        {
            DateTime ultima = new DateTime((lunaCB.SelectedIndex  + 2) > 12 ? anulDTP.Value.Year : anulDTP.Value.Year + 1,
               (lunaCB.SelectedIndex + 2) > 12 ? 1 : lunaCB.SelectedIndex +  2, 1);
            delaDTP.Value = new DateTime(anulDTP.Value.Year, lunaCB.SelectedIndex + 1, 1);
            panalaDTP.Value = new DateTime(anulDTP.Value.Year, lunaCB.SelectedIndex + 1, ultima.AddDays(-1).Day);
        }

        private void anulDTP_ValueChanged(object sender, EventArgs e)
        {
            delaDTP.Value = new DateTime(anulDTP.Value.Year, delaDTP.Value.Month, delaDTP.Value.Day);
            panalaDTP.Value = new DateTime(anulDTP.Value.Year, panalaDTP.Value.Month, panalaDTP.Value.Day);

        }

        private void fillToolStripButton_Click(object sender, EventArgs e)
        {
            try
            {
                
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }

        }

       

       


    }
}
